//
//  SellOutViewController.m
//  Exchange
//
//  Created by 张庆勇 on 2018/7/25.
//  Copyright © 2018年 张庆勇. All rights reserved.
//

#import "SellOutViewController.h"
#import "CellOrderinfoViewController.h"
#import "LoginViewController.h"
#import "BankWithSetViewController.h"
#import "CheckVersionAlearView.h"
#import "BindBankViewController.h"
#import "WOrderModle.h"
#import "IdentityAuthenticationViewController.h"
@interface SellOutViewController ()<UITextFieldDelegate>
@property (nonatomic,strong)NSMutableArray *dataArray;
@property (nonatomic,strong)NSString *asset; //卖出币种
@property (nonatomic,strong)NSString *sell_price;//卖出估价
@property (nonatomic,strong)NSString *min_amount;//最小购买量

@end

@implementation SellOutViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initUI];
    [self getBank];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(LoginSusess) name:LoginSusessNotificationse object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(getBankData:) name:bindbnakNotificationse object:nil];
    // 上拉加载
    WeakSelf
    WLRefreshGifHeader *header = [WLRefreshGifHeader headerWithRefreshingBlock:^{
        
        [weakSelf getData];
        
    }];
    [header beginRefreshing];
    self.tableview.mj_header = header;
}
- (void)getBankData:(NSNotification *)message
{
     [self getBank];
}
- (void)LoginSusess
{
    [self getBank];
    [self getUserInfo];
}
- (void)getUserInfo
{
    [HomeViewModel getUserWithDic:@{} url:getUser callBack:^(BOOL isSuccess, id callBack) {
        
        if (!isSuccess) {
            [self axcBasePopUpWarningAlertViewWithMessage:callBack[@"message"] view:kWindow];
        }
    }];
}
- (void)getBank
{
    WeakSelf
     _sellOutbutton.userInteractionEnabled = NO;
    [HomeViewModel getUserbankWithDic:@{} url:userbank callBack:^(BOOL isSuccess, id callBack) {
        if (isSuccess) {
            weakSelf.dataArray = callBack;
            weakSelf.sellOutbutton.userInteractionEnabled = YES;
        }
    }];
}
- (void)getData
{
    WeakSelf
    [HomeViewModel getC2CPriceInfoWithDic:@{} url:c2cPrice callBack:^(BOOL isSuccess, id callBack) {
        if (isSuccess)
        {
            weakSelf.assetLable.text = callBack[@"result"][@"asset"];
            weakSelf.sellOutPrice.text = [NSString stringWithFormat:@"%.2f",[callBack[@"result"][@"sell_price"] floatValue]];
            weakSelf.min_amount = callBack[@"result"][@"min_amount"];
            
            weakSelf.sellOutToal.placeholder = [NSString stringWithFormat:@"%@%@",Localized(@"C2C_Minimum_volume"),weakSelf.min_amount];
            [weakSelf.sellOutToal setValue:[ZBLocalized sharedInstance].C2CTextPColor forKeyPath:@"_placeholderLabel.textColor"];
            [weakSelf.sellOutToal setValue:AutoFont(18) forKeyPath:@"_placeholderLabel.font"];
            weakSelf.sellOutToal.tintColor = WHITECOLOR;
            [weakSelf.sellOutbutton setTitle:[NSString stringWithFormat:@"%@ %@ —> CNY ",Localized(@"C2C_Sell_ok"),weakSelf.assetLable.text] forState:0];
        }
         [weakSelf.tableview.mj_header endRefreshing];
    }];
}
- (void)setUIwithSet:(UILabel *)Lable text:(NSString *)text font:(UIFont *)font textColor:(UIColor *)textColor
{
    Lable.textColor = textColor;
    Lable.font = font;
    if (Lable ==self.tipsContontLable)
    {
        Lable.attributedText = [EXUnit finderattributedString:text attributedString:Localized(@"C2C_message_world") color:MAINTITLECOLOR font:AutoBoldFont(11)];
    }else
    {
        Lable.text = text;
    }
   
}
- (void)initUI
{
    self.tableview.backgroundColor = MAINBLACKCOLOR;
    self.tableview.showsVerticalScrollIndicator = NO;
    self.bgView.backgroundColor = MAINBLACKCOLOR;
    self.bgView2.backgroundColor = MAINBLACKCOLOR;
    self.bgView1.backgroundColor = [ZBLocalized sharedInstance].C2CboxBgColor;
    self.bgView1.layer.mask = [EXUnit ShapeLayerWithViewCGRect:self.bgView1 cornerRadius:4];
    self.headView.backgroundColor = [ZBLocalized sharedInstance].BgViewLightColor;
    
    //
    [self setUIwithSet:self.titleLable1 text:Localized(@"C2C_Sell_valuation") font:AutoBoldFont(12) textColor:[ZBLocalized sharedInstance].C2CTitleTextColor];
    [self setUIwithSet:self.sellOutPrice text:@"" font:AutoBoldFont(21) textColor:MAINTITLECOLOR];
    [self setUIwithSet:self.rightLable text:@"CNY" font:AutoBoldFont(12) textColor:MAINTITLECOLOR1];
    self.line1.backgroundColor =CELLCOLOR;
    //
    [self setUIwithSet:self.titleLable2 text:Localized(@"C2C_Sell_num") font:AutoBoldFont(12) textColor:[ZBLocalized sharedInstance].C2CTitleTextColor];
    
    self.sellOutNumber.placeholder = Localized(@"C2C_enter_quantity");
    [self.sellOutNumber setValue:[ZBLocalized sharedInstance].C2CTextPColor forKeyPath:@"_placeholderLabel.textColor"];
    [self.sellOutNumber setValue:AutoFont(18) forKeyPath:@"_placeholderLabel.font"];
    self.sellOutNumber.tintColor = MAINTITLECOLOR;
    self.sellOutNumber.textColor = MAINTITLECOLOR;
    [self.sellOutNumber addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    [self setUIwithSet:self.assetLable text:[AppDelegate shareAppdelegate].DICKEY font:AutoBoldFont(12) textColor:MAINTITLECOLOR1];
     self.line2.backgroundColor =CELLCOLOR;
    
    //
    [self setUIwithSet:self.titleLable3 text:Localized(@"C2C_money") font:AutoBoldFont(12) textColor:[ZBLocalized sharedInstance].C2CTitleTextColor];
    
    self.sellOutToal.placeholder = Localized(@"C2C_Minimum_volume");
    [self.sellOutToal setValue:[ZBLocalized sharedInstance].C2CTextPColor forKeyPath:@"_placeholderLabel.textColor"];
    [self.sellOutToal setValue:AutoFont(18) forKeyPath:@"_placeholderLabel.font"];
    self.sellOutToal.tintColor = MAINTITLECOLOR;
    self.sellOutToal.textColor = MAINTITLECOLOR;
    self.sellOutToal.delegate = self;
    self.line3.backgroundColor =CELLCOLOR;
    [self setUIwithSet:self.rightLable1 text:@"CNY" font:AutoBoldFont(12) textColor:MAINTITLECOLOR1];
    
    //
    [self setUIwithSet:self.titleLable4 text:Localized(@"C2C_Payment_method") font:AutoBoldFont(12) textColor:[ZBLocalized sharedInstance].C2CTitleTextColor];
    [self setUIwithSet:self.bankLable text:Localized(@"C2C_Bank_card") font:AutoBoldFont(21) textColor:MAINTITLECOLOR];
    //
    _sellOutbutton.backgroundColor = DIEECOLOR;
    _sellOutbutton.titleLabel.font = AutoBoldFont(15);
   
    KViewRadius(_sellOutbutton, 2);
    [self.sellOutbutton setTitle:[NSString stringWithFormat:@"%@ %@ —> CNY ",Localized(@"C2C_Sell_ok"),self.assetLable.text] forState:0];
    //
    
    [self setUIwithSet:self.messageLable text:Localized(@"C2C_merchants_message") font:AutoFont(12) textColor:MAINTITLECOLOR1];
    [self setUIwithSet:self.tipsLable text:Localized(@"C2C_Reminder") font:AutoFont(11) textColor:TABTITLECOLOR];
    [self setUIwithSet:self.tipsContontLable text:Localized(@"C2C_message") font:AutoFont(11) textColor:MAINTITLECOLOR1];
    
}
- (void)viewWillLayoutSubviews
{
    _bgView1.height = self.tipsContontLable.height +50;
    _bgView1.width = UIScreenWidth -RealValue_W(60);
    _bgView1.backgroundColor = [ZBLocalized sharedInstance].C2CboxBgColor;
    _bgView1.layer.mask = [EXUnit ShapeLayerWithViewCGRect:_bgView1 cornerRadius:4];
     _headView.height = _bgView1.height + 900;
}
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
 if (textField == _sellOutToal) {
    return NO;
  }else
 {
    return YES;
  }
}
- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc] init];
    }
    return _dataArray;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)textFieldDidChange :(UITextField *)TextField{
    if (TextField.text.length ==0 ||[NSString isEmptyString:TextField.text])
    {
        _sellOutToal.text = @"";
    }else
    {
         _sellOutToal.text = [NSString stringWithFormat:@"%.2f",TextField.text.floatValue * self.sellOutPrice.text.floatValue];
    }
    
 
}

- (IBAction)sellOutbutton:(LcButton *)sender {
   
    if (![EXUserManager isLogin])
    {
        [self SetThePassword];
         [sender stopAnimation];
        return;
    }
    WeakSelf
    if ([AppDelegate shareAppdelegate].isBecomeActive) {
        if ([EXUnit isOpenTouchid] && ![EXUnit isOpenGesture]) {
            [sender stopAnimation];
            [YWFingerprintVerification fingerprintVerificationCallBack:^(NSError *error) {
                if(!error){
                    //验证成功，主线程处理UI
                    dispatch_async(dispatch_get_global_queue(0, 0), ^{
                        // 处理耗时操作的代码块...
                        
                        //通知主线程刷新
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [weakSelf Buy:sender];
                        });
                        
                    });
                }else{
                    //验证成功，主线程处理UI
                    dispatch_async(dispatch_get_global_queue(0, 0), ^{
                        // 处理耗时操作的代码块...
                        
                        //通知主线程刷新
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [EXUserManager removeUserInfo];
                            [weakSelf SetThePassword];
                        });
                        
                    });
                    
                }
            }];
        }else if (![EXUnit isOpenTouchid] && [EXUnit isOpenGesture])
        {
            [sender stopAnimation];
            //验证手势密码
            [YWUnlockView showUnlockViewWithType:YWUnlockViewUnlock callBack:^(BOOL result) {
                if (result) {
                   [weakSelf Buy:sender];
                }else
                {
                    [EXUserManager removeUserInfo];
                    [weakSelf SetThePassword];
                }
                
                
            }];
            
        }else if (![EXUnit isOpenTouchid] && ![EXUnit isOpenGesture])
        {
           
            [weakSelf Buy:sender];
        }
    }else
    {
        [weakSelf Buy:sender];
    }
    
}
- (void)SetThePassword
{
    
    LoginViewController * loginView = [[LoginViewController alloc] init];
    [[EXUnit currentViewController] presentViewController:loginView animated:YES completion:nil];
}
- (void)Buy:(LcButton *)sender
{
    [AppDelegate shareAppdelegate].isBecomeActive = NO;
    if ([EXUserManager RealName].integerValue ==0) { //未认证
         [sender stopAnimation];
      [self popRealName:YES title:Localized(@"transaction_authenticated_title") message:Localized(@"transaction_authenticated_message")];
        
    }else if ([EXUserManager RealName].integerValue ==1 ||[EXUserManager RealName].integerValue ==4)//审核中
    {
         [sender stopAnimation];
         [EXUnit showMessage:Localized(@"C2C_under_review")];
     
        
    }else if ([EXUserManager RealName].integerValue ==3)//认证失败
    {
        [sender stopAnimation];
        [self popRealName:YES title:Localized(@"transaction_authenticated_title") message:Localized(@"transaction_authenticated_failed")];
   
        
    }else if ([EXUserManager RealName].integerValue ==2)//认证成功
    {
        
        if (self.dataArray.count==0)
        {
             [sender stopAnimation];
            [self popRealName:NO title:Localized(@"C2C_bank_card") message:Localized(@"C2C_bank_card_message")];
        }else
        {
             [sender stopAnimation];
            if (_sellOutToal.text.floatValue < _min_amount.floatValue) {
                
                [self axcBasePopUpWarningAlertViewWithMessage:[NSString stringWithFormat:@"%@%@%@",Localized(@"C2C_Sell_semail"),_min_amount, self.assetLable.text] view:kWindow];
                
                return;
            }
         
            BankWithSetViewController * Choosebank = [[BankWithSetViewController alloc] init];
            Choosebank.ischooseBank = YES;
            Choosebank.title = Localized(@"C2C_Choose_bank_card");
            [self.navigationController pushViewController:Choosebank animated:YES];
            WeakSelf
            Choosebank.addBankblock = ^(BankModle *modle) {
                if (![NSString isEmptyString:modle.ID]) {
                    [self POSTWithHost:@"" path:c2ctrade param:@{@"amount":weakSelf.sellOutNumber.text,@"type":@"2",@"user_bank_id":modle.ID} cache:NO completed:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                        
                        [sender stopAnimation];
                        
                        if ([responseObject[@"code"] integerValue]==0)//成功
                        {
                            WOrderModle * modle = [WOrderModle mj_objectWithKeyValues:responseObject[@"result"][@"order"]];
                            CellOrderinfoViewController *WOrderInfoVC = [[CellOrderinfoViewController alloc] init];
                            WOrderInfoVC.modle = modle;
                            WOrderInfoVC.dic = responseObject[@"result"][@"merchant"];
                            [self.navigationController pushViewController:WOrderInfoVC animated:YES];
                            weakSelf.sellOutToal.text = @"";
                            weakSelf.sellOutNumber.text = @"";
                            
                        }else
                        {
                            [self axcBasePopUpWarningAlertViewWithMessage:responseObject[@"message"] view:kWindow];
                        }
                        
                    } error:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                        [sender stopAnimation];
                    }];
                };
            };
        }
    }
    
   
   
}
- (void)popRealName:(BOOL)isRealName title:(NSString *)title message:(NSString *)message
{
    if (isRealName) {
        CheckVersionAlearView * aleartVC = [[CheckVersionAlearView alloc] initWithmessage:message
                                                                                 titleStr:title
                                                                                  openUrl:@""
                                                                                  confirm:Localized(@"transaction_OK")
                                                                                   cancel:Localized(@"transaction_cancel")
                                                                                    state:2
                                                                            RechargeBlock:^
                                            {
                                                
                                                IdentityAuthenticationViewController * idACationVC = [[IdentityAuthenticationViewController alloc] init];
                                                idACationVC.title = Localized(@"my_identity_authentication");
                                                [[EXUnit currentViewController].navigationController pushViewController:idACationVC animated:YES];
                                                
                                                
                                            }];
        aleartVC.animationStyle = LXASAnimationTopShake;
        [aleartVC showLXAlertView];
    }else
    {
        CheckVersionAlearView * aleartVC = [[CheckVersionAlearView alloc] initWithmessage:message
                                                                                 titleStr:title
                                                                                  openUrl:@""
                                                                                  confirm:Localized(@"transaction_OK")
                                                                                   cancel:Localized(@"transaction_cancel")
                                                                                    state:2
                                                                            RechargeBlock:^{
                                                                                
                                                                                BindBankViewController * bindbank = [[BindBankViewController alloc] init];
                                                                                bindbank.title = Localized(@"C2C_Bank_card_settings");
                                                                                [self.navigationController pushViewController:bindbank animated:YES];
                                                                                
                                                                            }];
        aleartVC.animationStyle = LXASAnimationTopShake;
        [aleartVC showLXAlertView];
    }
}
- (IBAction)Choosebutton:(UIButton *)sender {

}

@end
